<?php
/**
 * 函数库
 */
if (!defined('SYSTEM_ROOT')) { die('Insufficient Permissions'); }


/**
 * 错误码处理
 */
function errorJson($a = 100000,$b = "未知错误"){
    return json_encode(array("code" => $a, "msg" => $b));
}

/**
 * 加密密码
 */
function EncodePwd($pwd)
{
    return md5(md5(md5($pwd)));
}


/**
 * 清空缓冲区的内容
 * @note 已修复无法清除缓冲区的bug
 */
function Clean() {
    ob_clean();
}

/**
 * 打印可读的变量信息
 * @param mixed $var
 * @param bool $mode false = var_dump() | true = print_r()
 */
function dump($var , $mode = false) {
        echo '<pre>';
        if (!$mode) {
                var_dump($var);
        } else {
                print_r($var);
        }
        echo '</pre>';
}


/**
 * 获取用户ip地址
 */
function getIp() {
        $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
        if (!ip2long($ip)) {
                $ip = '';
        }
        return $ip;
}


/**
 * 获取前一个页面URL
 */
function referer(){

        return $_SERVER['HTTP_REFERER'];
}

/**
 * 获取当前页面URL
 */
function get_url_now(){
        $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        return $url;
}


/*
 * 关键字拆分
 * */
function keyWords($kw,$do_fork = true,$do_unit = true,$do_multi = true,$do_prop = false,$pri_dict = false){
//    //岐义处理
//    $do_fork = true;
//    //新词识别
//    $do_unit = true;
//    //多元切分
//    $do_multi = true;
//    //词性标注
//    $do_prop = false;
//    //是否预载全部词条
//    $pri_dict = false;

    //初始化类
    PhpAnalysis::$loadInit = false;
    $pa = new PhpAnalysis('utf-8', 'utf-8', $pri_dict);

    //载入词典
    $pa->LoadDict();

    //执行分词
    $pa->SetSource($kw);
    $pa->differMax = $do_multi;
    $pa->unitWord = $do_unit;
    $pa->StartAnalysis($do_fork);
    $okresult = $pa->GetFinallyResult(' ', $do_prop);
    $okresult = ltrim($okresult);
    $re = explode(' ', $okresult);
    return $re;
}

/**
 * 获取URL根域名
 */
function GetUrlToDomain($domain) {
    $re_domain = '';
    $domain_postfix_cn_array = array("com", "net", "org", "gov", "edu", "com.cn", "cn");
    $array_domain = explode(".", $domain);
    $array_num = count($array_domain) - 1;
    if ($array_domain[$array_num] == 'cn') {
        if (in_array($array_domain[$array_num - 1], $domain_postfix_cn_array)) {
            $re_domain = $array_domain[$array_num - 2] . "." . $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
        } else {
            $re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
        }
    } else {
        $re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
    }
    return $re_domain;
}


/**
 * 图片获取
 */
function getImg($jurl,$num){
    $t = json_decode($jurl,true);
    if(empty($t[$num]['url'])){
        $r = 'source/img/null.jpg';
    }else{
        $Url=$t[$num]['url'];
        $tempu=parse_url($Url);
        $message=$tempu['host'];
        if(GetUrlToDomain($message) == 'alicdn.com' || GetUrlToDomain($message) == 'tbcdn.cn'){
            $a = textMiddle($t[$num]['url'],'jpg_','.jpg');
            if(empty($a)){
                $r = $t[$num]['url'].'_300x300.jpg';
            } else {
                $r = $t[$num]['url'];
            }
        } else {
            $r = $t[$num]['url'];
        }

    }
    return $r;
}





/**
 * 折扣计算
 */
function discount($o_price,$d_price){
    if($o_price <= 0){
        return '全折';
    } else {
        $cm = $d_price / $o_price;
        if($cm == 1){
            return '全折';
        } else {
            $cm = $cm * 10;
            $cm = number_format($cm,3);
            $cm = substr(number_format($cm, 3, '.',','),0,-2);
            return $cm."折";
        }
    }
}

/*
 * 月份转换成英文函数
 * */
function transMonth($month){
    switch($month){
        case 1:
            $r = 'Jan';
            break;
        case 2:
            $r = 'Feb';
            break;
        case 3:
            $r = 'Mar';
            break;
        case 4:
            $r = 'Apr';
            break;
        case 5:
            $r = 'May';
            break;
        case 6:
            $r = 'Jun';
            break;
        case 7:
            $r = 'Jul';
            break;
        case 8:
            $r = 'Aug';
            break;
        case 9:
            $r = 'Sep';
            break;
        case 10:
            $r = 'Oct';
            break;
        case 11:
            $r = 'Nov';
            break;
        case 12:
            $r = 'Dec';
            break;
        default:
            $r = $month;
            break;
    }
    return $r;
}




/*
将URL中的某参数设为某值
*/
function url_set_value($url,$key,$value)
{
        $a=explode('?',$url);
        $url_f=$a[0];
        $query=$a[1];
        parse_str($query,$arr);
        $arr[$key]=$value;
        return $url_f.'?'.http_build_query($arr);
}

/**
 * 验证email地址格式
 */
function checkMail($email) {
        if (preg_match("/^[\w\.\-]+@\w+([\.\-]\w+)*\.\w+$/", $email) && strlen($email) <= 60) {
                return true;
        } else {
                return false;
        }
}

/**
 * (弃用)生成一个随机的字符串
 *
 * @param int $length
 * @param boolean $special_chars
 * @return string
 */
function getRandStr($length = 12, $special_chars = false) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        if ($special_chars) {
                $chars .= '!@#$%^&*()';
        }
        $randStr = '';
        for ($e = 0; $e < $length; $e++) {
                $randStr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $randStr;
}

/**
 * 获取两段文本之间的文本
 *
 * @param 完整的文本
 * @param 左边文本
 * @param 右边文本
 * 返回“左边文本”与“右边文本”之间的文本
 */
function textMiddle($text, $left, $right) {
        $loc1 = stripos($text, $left);
        if (is_bool($loc1)) { return ""; }
        $loc1 += strlen($left);
        $loc2 = stripos($text, $right, $loc1);
        if (is_bool($loc2)) { return ""; }
        return substr($text, $loc1, $loc2 - $loc1);
}

/**
 * 执行一个网络请求而不等待返回结果
 * @param string $url URL
 * @param string $post post数据包，留空为get
 * @param string $cookie cookies
 * @return bool fsockopen是否成功
 */
function sendRequest($url , $post = '' , $cookie = '') {
        if (function_exists('fsockopen')) {
                $matches = parse_url($url);
                $host = $matches['host'];
                if (substr($url, 0, 8) == 'https://') {
                        $host = 'ssl://' . $host;
                }
                $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
                $port = !empty($matches['port']) ? $matches['port'] : 80;
                if(!empty($post)) {
                        $out = "POST $path HTTP/1.1\r\n";
                        $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
                        $out .= "Host: $host\r\n";
                        $out .= "Connection: Close\r\n\r\n";
                        $out .= $post;
                } else {
                        $out = "GET $path HTTP/1.1\r\n";
                        $out .= "Host: $host\r\n";
                        $out .= "Connection: Close\r\n\r\n";
                }
                $fp = fsockopen($host, $port);
                if (!$fp) {
                        return false;
                } else {
                        stream_set_blocking($fp , 0);
                        stream_set_timeout($fp , 0);
                        fwrite($fp, $out);
                        fclose($fp);
                        return true;
                }
        } else {
                $x = new wcurl($url);
                $x->set(CURLOPT_CONNECTTIMEOUT , 1);
                $x->set(CURLOPT_TIMEOUT , 1);
                $x->addcookie($cookie);
                if (empty($post)) {
                        $x->post($post);
                } else {
                        $x->exec();
                }
                return true;
        }
}

/**
 * 页面重定向
 *
 * @param $url 地址
 */

function Redirect($url) {
        header("Location: ".$url);
        msg('<meta http-equiv="refresh" content="0; url='.htmlspecialchars($url).'" />请稍候......<br/><br/>如果您的浏览器没有自动跳转，请点击下面的链接',htmlspecialchars($url));
}

/**
 * 使用反斜线引用字符串或数组以便于SQL查询
 * 只引用'和\
 * @param $s 需要转义的
 * @return 转义结果
 */
function sqladds($s) {
        if (is_array($s)) {
                $r = array();
                foreach ($s as $key => $value) {
                        $k = str_replace('\'','\\\'', str_replace('\\','\\\\',$value));

                        if (!is_array($value)) {
                                $r[$k] = str_replace('\'','\\\'', str_replace('\\','\\\\',$value));
                        } else {
                                $r[$k] = sqladds($value);
                        }
                }
                return $r;
        } else {
                return str_replace('\'','\\\'', str_replace('\\','\\\\',$s));
        }
}

/**
 * 去除英文字母、数字、下划线以外所有字符
 * @param $s 需要处理的
 * @return 处理结果
 */
function onlyalnum($s) {
        if (is_array($s)) {
                $r = array();
                foreach ($s as $key => $value) {
                        $k = preg_replace('/[^a-zA-Z0-9._]*/','',$key);
                        if (!is_array($value)) {
                                $r[$k] = preg_replace('/[^a-zA-Z0-9._]*/','',$value);
                        } else {
                                $r[$k] = onlyalnum($value);
                        }
                }
                return $r;
        } else {
                return preg_replace('/[^a-zA-Z0-9._]*/','',$s);
        }
}

/**
 * 转为正数或者0
 * @param $s 需要转换的
 * @return 转换结果
 */

function topos($s) {
        return abs(intval($s));
}

/**
 * 执行一个通配符表达式匹配
 * [可当preg_match()的简化版本去理解]
 * @param string $exp 匹配表达式
 * @param string $str 在这个字符串内运行匹配
 * @param int $pat 规定匹配模式，0表示尽可能多匹配，1表示尽可能少匹配
 * @return array 匹配结果，$matches[0]将包含完整模式匹配到的文本， $matches[1] 将包含第一个捕获子组匹配到的文本，以此类推。
 */
function easy_match($exp, $str, $pat = 0) {
        $exp = str_ireplace('\\', '\\\\', $exp);
        $exp = str_ireplace('/', '\/', $exp);
        $exp = str_ireplace('?', '\?', $exp);
        $exp = str_ireplace('<', '\<', $exp);
        $exp = str_ireplace('>', '\>', $exp);
        $exp = str_ireplace('^', '\^', $exp);
        $exp = str_ireplace('$', '\$', $exp);
        $exp = str_ireplace('+', '\+', $exp);
        $exp = str_ireplace('(', '\(', $exp);
        $exp = str_ireplace(')', '\)', $exp);
        $exp = str_ireplace('[', '\[', $exp);
        $exp = str_ireplace(']', '\]', $exp);
        $exp = str_ireplace('|', '\|', $exp);
        $exp = str_ireplace('}', '\}', $exp);
        $exp = str_ireplace('{', '\{', $exp);
        if ($pat==0) {
                $z = '(.*)';
        } else {
                $z = '(.*?)';
        }
        $exp = str_ireplace('*', $z, $exp);
        $exp = '/' . $exp . '/';
        preg_match($exp, $str, $r);
        return $r;
}

/**
 * 执行一个全局通配符表达式匹配
 * [可当preg_match_all()的简化版本去理解]
 * @param string $exp 匹配表达式
 * @param string $str 在这个字符串内运行匹配
 * @param int $pat 规定匹配模式，0表示尽可能多匹配，1表示尽可能少匹配
 * @param int $flags 可以使用 PREG_PATTERN_ORDER 或 PREG_SET_ORDER 或 PREG_OFFSET_CAPTURE
 * @return array 匹配结果，数组排序通过flags指定。
 */
function easy_match_all($exp, $str, $pat = 0, $flags = PREG_PATTERN_ORDER) {
        $exp = str_ireplace('\\', '\\\\', $exp);
        $exp = str_ireplace('/', '\/', $exp);
        $exp = str_ireplace('?', '\?', $exp);
        $exp = str_ireplace('<', '\<', $exp);
        $exp = str_ireplace('>', '\>', $exp);
        $exp = str_ireplace('^', '\^', $exp);
        $exp = str_ireplace('$', '\$', $exp);
        $exp = str_ireplace('+', '\+', $exp);
        $exp = str_ireplace('(', '\(', $exp);
        $exp = str_ireplace(')', '\)', $exp);
        $exp = str_ireplace('[', '\[', $exp);
        $exp = str_ireplace(']', '\]', $exp);
        $exp = str_ireplace('|', '\|', $exp);
        $exp = str_ireplace('}', '\}', $exp);
        $exp = str_ireplace('{', '\{', $exp);
        if ($pat==0) {
                $z = '(.*)';
        } else {
                $z = '(.*?)';
        }
        $exp = str_ireplace('*', $z, $exp);
        $exp = '/' . $exp . '/';
        preg_match($exp, $str, $r, $flags);
        return $r;
}

/**
 * 根据文件名称获取扩展名
 * @param string $name 文件名
 * @return string 扩展名（不带.）
 */
function get_extname($name) {
        return pathinfo($name, PATHINFO_EXTENSION);
}

/**
 * 确定一个域名属于哪个公司
 */
function get_c_url($url){
        if(!empty($url)){
                $url = parse_url($url);
                $url = $url['host'];
                if($url == "detail.tmall.com"){
                        return "Tmall";
                }
                elseif($url == "item.taobao.com"){
                        return "Taobao";
                }
                elseif($url == "item.jd.com") {
                        return "JD";
                } else {
                        return "嘿~o(^▽^)o";
                }
        }
}


/**
 * 根据扩展名获取文件的MIME
 * @param string $ext 扩展名
 * @return string MIME
 */
function get_mime($ext) {
        static $mime_types = array(
            'apk'     => 'application/vnd.android.package-archive',
            '3gp'     => 'video/3gpp',
            'ai'      => 'application/postscript',
            'aif'     => 'audio/x-aiff',
            'aifc'    => 'audio/x-aiff',
            'aiff'    => 'audio/x-aiff',
            'asc'     => 'text/plain',
            'atom'    => 'application/atom+xml',
            'au'      => 'audio/basic',
            'avi'     => 'video/x-msvideo',
            'bcpio'   => 'application/x-bcpio',
            'bin'     => 'application/octet-stream',
            'bmp'     => 'image/bmp',
            'cdf'     => 'application/x-netcdf',
            'cgm'     => 'image/cgm',
            'class'   => 'application/octet-stream',
            'cpio'    => 'application/x-cpio',
            'cpt'     => 'application/mac-compactpro',
            'csh'     => 'application/x-csh',
            'css'     => 'text/css',
            'dcr'     => 'application/x-director',
            'dif'     => 'video/x-dv',
            'dir'     => 'application/x-director',
            'djv'     => 'image/vnd.djvu',
            'djvu'    => 'image/vnd.djvu',
            'dll'     => 'application/octet-stream',
            'dmg'     => 'application/octet-stream',
            'dms'     => 'application/octet-stream',
            'doc'     => 'application/msword',
            'dtd'     => 'application/xml-dtd',
            'dv'      => 'video/x-dv',
            'dvi'     => 'application/x-dvi',
            'dxr'     => 'application/x-director',
            'eps'     => 'application/postscript',
            'etx'     => 'text/x-setext',
            'exe'     => 'application/octet-stream',
            'ez'      => 'application/andrew-inset',
            'flv'     => 'video/x-flv',
            'gif'     => 'image/gif',
            'gram'    => 'application/srgs',
            'grxml'   => 'application/srgs+xml',
            'gtar'    => 'application/x-gtar',
            'gz'      => 'application/x-gzip',
            'hdf'     => 'application/x-hdf',
            'hqx'     => 'application/mac-binhex40',
            'htm'     => 'text/html',
            'html'    => 'text/html',
            'ice'     => 'x-conference/x-cooltalk',
            'ico'     => 'image/x-icon',
            'ics'     => 'text/calendar',
            'ief'     => 'image/ief',
            'ifb'     => 'text/calendar',
            'iges'    => 'model/iges',
            'igs'     => 'model/iges',
            'jnlp'    => 'application/x-java-jnlp-file',
            'jp2'     => 'image/jp2',
            'jpe'     => 'image/jpeg',
            'jpeg'    => 'image/jpeg',
            'jpg'     => 'image/jpeg',
            'js'      => 'application/x-javascript',
            'kar'     => 'audio/midi',
            'latex'   => 'application/x-latex',
            'lha'     => 'application/octet-stream',
            'lzh'     => 'application/octet-stream',
            'm3u'     => 'audio/x-mpegurl',
            'm4a'     => 'audio/mp4a-latm',
            'm4p'     => 'audio/mp4a-latm',
            'm4u'     => 'video/vnd.mpegurl',
            'm4v'     => 'video/x-m4v',
            'mac'     => 'image/x-macpaint',
            'man'     => 'application/x-troff-man',
            'mathml'  => 'application/mathml+xml',
            'me'      => 'application/x-troff-me',
            'mesh'    => 'model/mesh',
            'mid'     => 'audio/midi',
            'midi'    => 'audio/midi',
            'mif'     => 'application/vnd.mif',
            'mov'     => 'video/quicktime',
            'movie'   => 'video/x-sgi-movie',
            'mp2'     => 'audio/mpeg',
            'mp3'     => 'audio/mpeg',
            'mp4'     => 'video/mp4',
            'mpe'     => 'video/mpeg',
            'mpeg'    => 'video/mpeg',
            'mpg'     => 'video/mpeg',
            'mpga'    => 'audio/mpeg',
            'ms'      => 'application/x-troff-ms',
            'msh'     => 'model/mesh',
            'mxu'     => 'video/vnd.mpegurl',
            'nc'      => 'application/x-netcdf',
            'oda'     => 'application/oda',
            'ogg'     => 'application/ogg',
            'ogv'     => 'video/ogv',
            'pbm'     => 'image/x-portable-bitmap',
            'pct'     => 'image/pict',
            'pdb'     => 'chemical/x-pdb',
            'pdf'     => 'application/pdf',
            'pgm'     => 'image/x-portable-graymap',
            'pgn'     => 'application/x-chess-pgn',
            'pic'     => 'image/pict',
            'pict'    => 'image/pict',
            'png'     => 'image/png',
            'pnm'     => 'image/x-portable-anymap',
            'pnt'     => 'image/x-macpaint',
            'pntg'    => 'image/x-macpaint',
            'ppm'     => 'image/x-portable-pixmap',
            'ppt'     => 'application/vnd.ms-powerpoint',
            'ps'      => 'application/postscript',
            'qt'      => 'video/quicktime',
            'qti'     => 'image/x-quicktime',
            'qtif'    => 'image/x-quicktime',
            'ra'      => 'audio/x-pn-realaudio',
            'ram'     => 'audio/x-pn-realaudio',
            'ras'     => 'image/x-cmu-raster',
            'rdf'     => 'application/rdf+xml',
            'rgb'     => 'image/x-rgb',
            'rm'      => 'application/vnd.rn-realmedia',
            'roff'    => 'application/x-troff',
            'rtf'     => 'text/rtf',
            'rtx'     => 'text/richtext',
            'sgm'     => 'text/sgml',
            'sgml'    => 'text/sgml',
            'sh'      => 'application/x-sh',
            'shar'    => 'application/x-shar',
            'silo'    => 'model/mesh',
            'sit'     => 'application/x-stuffit',
            'skd'     => 'application/x-koan',
            'skm'     => 'application/x-koan',
            'skp'     => 'application/x-koan',
            'skt'     => 'application/x-koan',
            'smi'     => 'application/smil',
            'smil'    => 'application/smil',
            'snd'     => 'audio/basic',
            'so'      => 'application/octet-stream',
            'spl'     => 'application/x-futuresplash',
            'src'     => 'application/x-wais-source',
            'sv4cpio' => 'application/x-sv4cpio',
            'sv4crc'  => 'application/x-sv4crc',
            'svg'     => 'image/svg+xml',
            'swf'     => 'application/x-shockwave-flash',
            't'       => 'application/x-troff',
            'tar'     => 'application/x-tar',
            'tcl'     => 'application/x-tcl',
            'tex'     => 'application/x-tex',
            'texi'    => 'application/x-texinfo',
            'texinfo' => 'application/x-texinfo',
            'tif'     => 'image/tiff',
            'tiff'    => 'image/tiff',
            'tr'      => 'application/x-troff',
            'tsv'     => 'text/tab-separated-values',
            'txt'     => 'text/plain',
            'ustar'   => 'application/x-ustar',
            'vcd'     => 'application/x-cdlink',
            'vrml'    => 'model/vrml',
            'vxml'    => 'application/voicexml+xml',
            'wav'     => 'audio/x-wav',
            'wbmp'    => 'image/vnd.wap.wbmp',
            'wbxml'   => 'application/vnd.wap.wbxml',
            'webm'    => 'video/webm',
            'wml'     => 'text/vnd.wap.wml',
            'wmlc'    => 'application/vnd.wap.wmlc',
            'wmls'    => 'text/vnd.wap.wmlscript',
            'wmlsc'   => 'application/vnd.wap.wmlscriptc',
            'wmv'     => 'video/x-ms-wmv',
            'wrl'     => 'model/vrml',
            'xbm'     => 'image/x-xbitmap',
            'xht'     => 'application/xhtml+xml',
            'xhtml'   => 'application/xhtml+xml',
            'xls'     => 'application/vnd.ms-excel',
            'xml'     => 'application/xml',
            'xpm'     => 'image/x-xpixmap',
            'xsl'     => 'application/xml',
            'xslt'    => 'application/xslt+xml',
            'xul'     => 'application/vnd.mozilla.xul+xml',
            'xwd'     => 'image/x-xwindowdump',
            'xyz'     => 'chemical/x-xyz',
            'zip'     => 'application/zip'
        );
        return isset($mime_types[$ext]) ? $mime_types[$ext] : 'application/octet-stream';
}